#include "YUVReader.h"
#include "base/YUVImage.h"
#include <cstddef>
#include <memory>

namespace Sivin {
  int YUVReader::open(std::string path, int width, int height, YUVImage::Format format) {
    if (width * height <= 0) {
      return -1;
    }
    mYuvStream = std::make_unique<std::ifstream>();
    mYuvStream->open(path, std::fstream::in | std::fstream::binary);
    if (mYuvStream->is_open()) {
      mWidth = width;
      mHeight = height;
      mFmt = format;
      return 0;
    }
    mYuvStream->close();
    return -1;
  }

  int YUVReader::readFrame(std::unique_ptr<YUVImage> &image) {

    int size = mWidth * mHeight;
    char *y_Data = new char[size];

    mYuvStream->read(y_Data, size);
    if (!mYuvStream->good()) {
      delete[] y_Data;
      return -1;
    }

    char *u_Data = new char[size / 4];
    mYuvStream->read(u_Data, size / 4);
    if (!mYuvStream->good()) {
      delete[] u_Data;
      return -1;
    }

    char *v_Data = new char[size / 4];
    mYuvStream->read(v_Data, size / 4);
    if (!mYuvStream->good()) {
      delete[] v_Data;
      return -1;
    }

    YUVImage *img = new YUVImage(mWidth, mHeight, mFmt);
    img->setData(y_Data, u_Data, v_Data);

    image = std::unique_ptr<YUVImage>(img);
    return 0;
  }

  void YUVReader::colse() {
    if (mYuvStream != nullptr) {
      mYuvStream->close();
    }
  }


}// namespace Sivin